<?php
class ChangePasswordForm extends BaseForm {
  const FORM_NAME                     = 'frm';

  const FIELD_CURRENT_PASSWORD        = 'current_password';
  const FIELD_NEW_PASSWORD            = 'new_password';
  const FIELD_RENEW_PASSWORD          = 'renew_password';

  public function configure() {

    $widgets = array(
            self::FIELD_CURRENT_PASSWORD => new sfWidgetFormInputPassword(array(), array('maxlength' => 255)),
            self::FIELD_NEW_PASSWORD => new sfWidgetFormInputPassword(array(), array('maxlength' => 255)),
            self::FIELD_RENEW_PASSWORD => new sfWidgetFormInputPassword(array(), array('maxlength' => 255))
    );

    $labels = array(
            self::FIELD_CURRENT_PASSWORD => 'Current Password<req />',
            self::FIELD_NEW_PASSWORD => 'New Password<req />',
            self::FIELD_RENEW_PASSWORD => 'Confirm Password<req />'
    );

    $this->setWidgets($widgets);
    $this->widgetSchema->setLabels($labels);

    $validators = array(
            self::FIELD_CURRENT_PASSWORD => new sfValidatorString(array(), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_CURRENT_PASSWORD])))),
            self::FIELD_NEW_PASSWORD => new sfValidatorString(array('min_length' => 6), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_NEW_PASSWORD])), 'min_length' => $labels[self::FIELD_NEW_PASSWORD] . ' should be at least 6 characters long'))
    );

    $this->setValidators($validators);
    $this->validatorSchema->setPostValidator(new sfValidatorCallback(array('callback' => array($this, 'postValidator'))));

    $this->widgetSchema->setNameFormat(self::FORM_NAME . '[%s]');

    $this->validatorSchema->setOption('allow_extra_fields', true);
    $this->validatorSchema->setOption('filter_extra_fields', false);
  }

  public function postValidator($validator, $values) {
    if (trim($values[self::FIELD_CURRENT_PASSWORD]) != '' && trim($values[self::FIELD_NEW_PASSWORD]) != '' && trim($values[self::FIELD_RENEW_PASSWORD]) != '') {

      $user = USERTable::getInstance()->findByUsername(sfContext::getInstance()->getUser()->getAttribute(Constants::SESSION_USERNAME));

      if (StringUtil::hashPassword(trim($values[self::FIELD_CURRENT_PASSWORD]), $user->getSalt()) !== $user->getPassword()) {
        $error = new sfValidatorError($validator, 'Current password is invalid');
        throw new sfValidatorErrorSchema($validator, array(self::FIELD_CURRENT_PASSWORD => $error));
      }

      if (trim($values[self::FIELD_NEW_PASSWORD]) !== trim($values[self::FIELD_RENEW_PASSWORD])) {
        $error = new sfValidatorError($validator, LangUtil::getText('error_mismatch_conf_password'));
        throw new sfValidatorErrorSchema($validator, array(self::FIELD_RENEW_PASSWORD => $error));
      }
    }

    return $values;
  }
}

?>